package net.aiform.security;

import java.awt.Font;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.ServletException;

import net.aiform.bean.Constant;

import java.io.IOException;

public class CertPic {
	private synchronized Font getFonts(Random random) {
		return new Font("Arial", Font.PLAIN, 18);
	}

	private synchronized Color getRandColor(int fc, int bc, Random random) {
		if (fc > 255) fc = 255;
		if (bc > 255) bc = 255;
		int r = fc + random.nextInt(bc - fc - 6);
		int g = fc + random.nextInt(bc - fc - 4);
		int b = fc + random.nextInt(bc - fc - 8);
		return new Color(r, g, b);
	}

	public synchronized void getRand(HttpServletRequest request, HttpServletResponse response, int width, int height, int length) throws ServletException, IOException {
		System.setProperty("java.awt.headless", "true");
		HttpSession session = request.getSession();
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics();
		Random random = new Random();
		g.fillRect(0, 0, width, height);
		g.setColor(Color.black);
		g.drawRect(0, 0, width - 1, height - 1);
		g.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, 18));
		g.setColor(getRandColor(111, 133, random));
		for (int i = 0; i < 7; i++) {
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int xl = random.nextInt(15);
			int yl = random.nextInt(17);
			g.setColor(new Color(random.nextInt(101), random.nextInt(111), random.nextInt(121)));
			g.drawLine(x, y, xl, yl);
		}
		g.setColor(getRandColor(130, 150, random));
		String sRand = "";
		String randStr = "";
		for (int i = 0; i < length; i++) {
			sRand = "";
			g.setFont(getFonts(random));
			g.setColor(new Color(random.nextInt(101), random.nextInt(111), random.nextInt(121)));
			String rand = String.valueOf(getRandomString(random.nextInt(36)));
			sRand += rand;
			randStr += rand;
			g.translate(random.nextInt(3), random.nextInt(3));
			g.drawString(sRand, 13 * i, 16);
		}
		session.removeAttribute(Constant.CERTPIC);
		session.setAttribute(Constant.CERTPIC, randStr);
		g.dispose();
		ImageIO.write(image, "JPEG", response.getOutputStream());
	}

	private String getRandomString(int num) {
		String randString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		return String.valueOf(randString.charAt(num));
	}
}
